package com.shqcjd.sinopecdemomobile.ui.activity.problem;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.app.MyApp;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.eventbus.ReloginEvent;
import com.shqcjd.sinopecdemomobile.model.pojo.OfflineProblemBean;
import com.shqcjd.sinopecdemomobile.model.pojo.ProblemSubmit;
import com.shqcjd.sinopecdemomobile.model.pojo.ProblemType;
import com.shqcjd.sinopecdemomobile.model.pojo.UploadFileRet;
import com.shqcjd.sinopecdemomobile.ui.activity.QRcodeActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.WaitingAnswerActivity;
import com.shqcjd.sinopecdemomobile.ui.adapter.UploadImageAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.AlbumUtils;
import com.shqcjd.sinopecdemomobile.util.DateUtil;
import com.shqcjd.sinopecdemomobile.util.MyGlideEngine;
import com.shqcjd.sinopecdemomobile.util.PrefUtils;
import com.shqcjd.sinopecdemomobile.util.SpacesItemDecoration;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;
import com.shqcjd.sinopecdemomobile.util.UIUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 问题反馈
 */
public class ProblemFeedbackActivity extends BaseActivity {
    private final int IMAGE_FILE_RESULT_CODE = 2;
    private static final int REQUEST_CODE = 1000;
    private static final int SUBMIT_PROBLEM = 100;//提交问题
    private static final int GUIDANCE = 200;//请求片区经理远程指导
    @BindView(R.id.iv_toolbar_back)
    ImageView ivToolbarBack;
    @BindView(R.id.tv_toolbar_center)
    TextView tvToolbarCenter;
    @BindView(R.id.et_eqpt_code)
    EditText etEqptCode;
    @BindView(R.id.ib_scan_btn)
    ImageButton ibScanBtn;
    @BindView(R.id.et_task_code)
    EditText etTaskCode;
    @BindView(R.id.et_info)
    EditText etInfo;
    @BindView(R.id.rv_img_list)
    RecyclerView rvImgList;
    @BindView(R.id.fl_offline_save_btn)
    FrameLayout flOfflineSaveBtn;
    @BindView(R.id.fl_remote_btn)
    FrameLayout flRemoteBtn;
    @BindView(R.id.tv_submit_btn)
    TextView tvSubmitBtn;
    @BindView(R.id.id_flowlayout)
    TagFlowLayout flowlayout;
    private Context mContext;
    private List<String> mList = new ArrayList<>();
    private UploadImageAdapter uploadImageAdapter;
    private ArrayList<String> mTypeVals = new ArrayList<>();
    private List<Integer> ids = new ArrayList<>();
    private TagAdapter flowLayoutAdapter;
    private String projectName;
    private String taskCode;
    private long offlineProblemId;
    private Integer managerUserId;
    private List<Integer> types;
    private OfflineProblemBean offlineProblemBean;
    private String kks;
    private String taskId;
    private AgoraAPIOnlySignal agoraAPIOnlySignal;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_problem_feedback;
    }

    @Override
    public void initView() {
        mContext = this;
        agoraAPIOnlySignal = MyApp.the().getmAgoraAPI();
        tvToolbarCenter.setText("提交问题");
        offlineProblemId = getIntent().getLongExtra("offlineProblemId", -1);
        projectName = getIntent().getStringExtra("projectName");
        kks = getIntent().getStringExtra("kks");
        taskCode = getIntent().getStringExtra("taskCode");
        taskId = getIntent().getStringExtra("taskId");

        if (etTaskCode != null) {
            etTaskCode.setText(taskId);
        }
        if (kks != null) {
            etEqptCode.setText(kks);
        }

        uploadImageAdapter = new UploadImageAdapter(mList, mContext, 8);
        rvImgList.setLayoutManager(new GridLayoutManager(mContext, 4));
        int leftRight = UIUtils.dip2px(5);
        int topBottom = UIUtils.dip2px(5);
        rvImgList.addItemDecoration(new SpacesItemDecoration(leftRight, topBottom));
        rvImgList.setAdapter(uploadImageAdapter);
        uploadImageAdapter.setOnClickDialogListener(new UploadImageAdapter.setOnClickItemAdapterListener() {
            @Override
            public void onClickAddPic(int pos) {
                RequestLocationAndCallPermission();
            }

            @Override
            public void onClickDeletePic(int pos) {
                deletePic(pos);
            }
        });


        etEqptCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                getTagType(s.toString().trim());
            }
        });
    }

    private void getTagType(String kks) {
        ApiService.getTagType(kks)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<String>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<String>> retData) {
                        if (retData.retCode == 10000) {
                            mTypeVals.clear();
                            for (String type : retData.data) {
                                mTypeVals.add(type);

                            }
                            TagAdapter tagAdapter = new TagAdapter<String>(mTypeVals.toArray(new String[mTypeVals.size()])) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.tv_tag,
                                            flowlayout, false);
                                    tv.setText(s);
                                    return tv;
                                }

                            };
                            flowlayout.setAdapter(tagAdapter);
                            //判断离线保存
                            if (types != null) {
                                Set<Integer> set = new HashSet<>(types);
                                tagAdapter.setSelectedList(set);
                            }
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                    }
                });
    }

    @Override
    public void initData() {
        //判断是否为离线问题
        if (offlineProblemId != -1) {
            offlineProblemBean = MyApp.getmDaoSession().getOfflineProblemBeanDao().load(offlineProblemId);
            etEqptCode.setText(offlineProblemBean.getKks() == null ? "" : offlineProblemBean.getKks());
            etTaskCode.setText(offlineProblemBean.getTaskId()==null?"": offlineProblemBean.getTaskId());
            etInfo.setText(offlineProblemBean.getProblemInfo()==null?"": offlineProblemBean.getProblemInfo());
            //问题类型
            if (offlineProblemBean.getTypes().size() > 0) {
                types = offlineProblemBean.getTypes();
            }
            //离线图片列表
            if (offlineProblemBean.getImgs()!=null) {
                for (String imgurl : offlineProblemBean.getImgs()) {
                    addPic(imgurl);
                }
            }
        }

//        getTypeList();
        getTagType(kks);
    }

    /**
     * 获取问题类型
     */
    private void getTypeList() {
        ApiService.getTypeList("problem_type")
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<ProblemType>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在获取数据...");
                    }

                    @Override
                    public void _onNext(ResponseData<List<ProblemType>> retData) {
                        if (retData.retCode == 10000) {
                            for (ProblemType type : retData.data) {
                                mTypeVals.add(type.name);

                            }
                            TagAdapter tagAdapter = new TagAdapter<String>(mTypeVals.toArray(new String[mTypeVals.size()])) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.tv_tag,
                                            flowlayout, false);
                                    tv.setText(s);
                                    return tv;
                                }

                            };
                            flowlayout.setAdapter(tagAdapter);
                            //判断离线保存
                            if (types != null) {
                                Set<Integer> set = new HashSet<>(types);
                                tagAdapter.setSelectedList(set);
                            }




                        } else {
                            ToastUtils.showShort(mContext, "获取问题类型失败!");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    public void RequestLocationAndCallPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Matisse.from(ProblemFeedbackActivity.this)
                                    .choose(MimeType.ofImage()) // 选择 mime 的类型
                                    .countable(false)
                                    .maxSelectable(8) // 图片选择的最多数量
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f) // 缩略图的比例
                                    .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                                    .theme(R.style.Matisse_Zhihu)
                                    .capture(true)//选择照片时，是否显示拍照
                                    .captureStrategy(new CaptureStrategy(true, getPackageName()))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                                    .forResult(IMAGE_FILE_RESULT_CODE); // 设置作为标记的请求码
                        } else {

                        }
                    }
                });
    }

    public void addPic(String uri) {
        if (mList.size() + 1 > 8) {
            ToastUtils.showShort(mContext, "上传图片超过8张");
            return;
        }
        mList.add(uri);
        uploadImageAdapter.notifyDataSetChanged();
    }

    public void deletePic(int pos) {
        mList.remove(pos);
        uploadImageAdapter.notifyDataSetChanged();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_FILE_RESULT_CODE && resultCode == RESULT_OK) {
            //图片上传
            if (data != null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri uri : uris) {
                    try {
                        String albumStringPath = AlbumUtils.getRealFilePath(this, uri);
                        addPic(albumStringPath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        } else if (REQUEST_CODE == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            etEqptCode.setText(value);
        }
    }

    @OnClick({R.id.iv_toolbar_back, R.id.ib_scan_btn, R.id.fl_offline_save_btn, R.id.fl_remote_btn, R.id.tv_submit_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_toolbar_back:
                finish();
                break;
            case R.id.ib_scan_btn://扫码
                RxPermissions permissions = new RxPermissions(this);
                permissions.setLogging(true);
                permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    startActivityForResult(new Intent(ProblemFeedbackActivity.this, QRcodeActivity.class), REQUEST_CODE);
                                } else {
                                    ToastUtils.show(ProblemFeedbackActivity.this, "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                }
                            }
                        });
                break;
            case R.id.fl_offline_save_btn://离线保存
                offlineSave();
                break;
            case R.id.fl_remote_btn://远程指导
                //登录成功发起远程指导
                if (agoraAPIOnlySignal.getStatus() == 2) {//0: 用户未登录。 1: 用户正在登录。 2: 用户已登录 3: 用户正在重建连接
                    getManagerId();
                } else {
                    int userId = PrefUtils.getInt(this, PrefUtils.USER_ID, -1);
                    agoraAPIOnlySignal.logout();
                    //登录成功后发起远程指导
                    agoraAPIOnlySignal.login2(getString(R.string.agora_app_id), userId + "", "_no_need_token", 0, "", 5, 3);
                }

                break;
            case R.id.tv_submit_btn://提交
                submitProblem(SUBMIT_PROBLEM);
                break;
        }
    }

    private void getManagerId() {
        ApiService.getManagerUserId(taskId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在获取信息...");
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> retData) {
                        if (retData.retCode == 10000) {
                            managerUserId = retData.data;
                            //判断片区经理是否在线
                            agoraAPIOnlySignal.queryUserStatus(managerUserId + "");

                        } else {
                            ToastUtils.showShort(mContext,"获取信息失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext,errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    /**
     * 片区经理离线提示
     */
    private void showOfflinePrompt() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.dialog_offline_prompt, false)
                .show();

        View customeView = dialog.getCustomView();
        customeView.findViewById(R.id.btn_dialog_commit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                submitProblem(SUBMIT_PROBLEM);
            }
        });
        customeView.findViewById(R.id.btn_dialog_finish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });


    }

    /**
     * 离线保存
     */
    private void offlineSave() {
        int loginId = PrefUtils.getInt(mContext, PrefUtils.USER_ID, -1);
        String eqptCode = etEqptCode.getText().toString().trim();
        String taskId = etTaskCode.getText().toString().trim();
        String info = etInfo.getText().toString().trim();
        Set<Integer> selectedList = flowlayout.getSelectedList();
        List typelist = new ArrayList(selectedList);

        if (offlineProblemBean != null) {//离线更新数据
            OfflineProblemBean updateOffline = new OfflineProblemBean(offlineProblemBean.getId(), projectName, eqptCode, taskCode,taskId, info, typelist, mList, DateUtil.getCurTimeLong(),loginId);
            MyApp.getmDaoSession().getOfflineProblemBeanDao().update(updateOffline);
            ToastUtils.showShort(mContext, "离线更新成功");
        } else {
            OfflineProblemBean offlineProblemBean;
            if (mList.size() > 0) {
                offlineProblemBean = new OfflineProblemBean(null, projectName, eqptCode, taskCode,taskId, info, typelist, mList, DateUtil.getCurTimeLong(), loginId);
            } else {
                offlineProblemBean = new OfflineProblemBean(null, projectName, eqptCode, taskCode,taskId, info, typelist, null, DateUtil.getCurTimeLong(), loginId);
            }
            MyApp.getmDaoSession().getOfflineProblemBeanDao().insert(offlineProblemBean);
            ToastUtils.showShort(mContext, "离线保存成功");
        }

    }

    /**
     * 给片区经理发起指导请求
     */
    private void guidanceRequest() {
        String eqptCode = etEqptCode.getText().toString().trim();
        String taskId = etTaskCode.getText().toString().trim();
        String info = etInfo.getText().toString().trim();
        Set<Integer> selectedList = flowlayout.getSelectedList();
        List<String> typeList = new ArrayList<>();
        for (Integer integer : selectedList) {
            typeList.add(mTypeVals.get(integer));
        }
        String typeString = typeList.toString().replace("[", "").replace("]", "");
        if (TextUtils.isEmpty(info)) {
            ToastUtils.showShort(this, "请输入问题描述");
            return;
        }
        ProblemSubmit problemSubmit = new ProblemSubmit(eqptCode, info, typeString,taskId, ids);
        ApiService.requestGuidance(new Gson().toJson(problemSubmit))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在提交数据...");
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> retData) {
                        if (retData.retCode == 10000) {
                            ToastUtils.showShort(mContext, "提交数据成功！");
                            Intent intent = new Intent(mContext, WaitingAnswerActivity.class);
                            intent.putExtra("remoteId", managerUserId);
                            intent.putExtra("problemFeedbackId", retData.data + "");
                            intent.putExtra("taskId", etTaskCode.getText().toString().trim());
                            intent.putExtra("kks",etEqptCode.getText().toString().trim());
                            startActivity(intent);
                            finish();

                        } else {
                            ToastUtils.showShort(mContext, "提交数据失败！");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    /**
     * 提交
     */
    private void submitProblem(int type) {
        String eqptCode = etEqptCode.getText().toString().trim();
        String info = etInfo.getText().toString().trim();
        Set<Integer> selectedList = flowlayout.getSelectedList();
        if (TextUtils.isEmpty(info)) {
            ToastUtils.showShort(this, "请输入问题描述");
            return;
        }
        if (mList.size() > 0) {
            uploadImage(type);
        } else {
            if (type == SUBMIT_PROBLEM) {
                submitContent();
            } else if (type == GUIDANCE) {
                guidanceRequest();
            }
        }

    }

    /**
     * 上传图片
     *
     * @param type
     */
    private void uploadImage(int type) {
        List<File> files = new ArrayList<>();
        for (String uri : mList) {
            files.add(new File(uri));
        }
        ApiService.uploadMultiAttachment(files)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<UploadFileRet>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在上传图片...");
                    }

                    @Override
                    public void _onNext(ResponseData<List<UploadFileRet>> retData) {
                        if (retData.retCode == 10000) {
                            for (UploadFileRet file : retData.data) {
                                ids.add(file.id);
                            }
                            if (type == SUBMIT_PROBLEM) {
                                submitContent();
                            } else if (type == GUIDANCE) {
                                guidanceRequest();
                            }
                        } else {
                            ToastUtils.showShort(mContext, "上传图片失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        Logger.i("上传图片:" + errorMessage);
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void submitContent() {
        String eqptCode = etEqptCode.getText().toString().trim();
        String taskId = etTaskCode.getText().toString().trim();
        String info = etInfo.getText().toString().trim();
        Set<Integer> selectedList = flowlayout.getSelectedList();
        List<String> typeList = new ArrayList<>();
        for (Integer integer : selectedList) {
            typeList.add(mTypeVals.get(integer));
        }
        String typeString = typeList.toString().replace("[", "").replace("]", "");
        if (TextUtils.isEmpty(info)) {
            ToastUtils.showShort(this, "请输入问题描述");
            return;
        }
        ProblemSubmit problemSubmit = new ProblemSubmit(eqptCode, info, typeString,taskId, ids);
        ApiService.submitProblem(new Gson().toJson(problemSubmit))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在提交数据...");
                    }

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData.retCode == 10000) {
                            if (offlineProblemBean != null) {//有离线数据，当提交数据后，删除本地离线数据
                                MyApp.getmDaoSession().getOfflineProblemBeanDao().deleteByKey(offlineProblemBean.getId());
                            }

                            ToastUtils.showShort(mContext, "提交数据成功！");
                            finish();
                        } else {
                            ToastUtils.showShort(mContext, "提交数据失败！");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        addCallback();
    }

    private void addCallback() {
        agoraAPIOnlySignal.callbackSet(new AgoraAPI.CallBack() {
            @Override
            public void onLogout(int i) {//103	该账户已在别处登录
                Logger.i("Agora 信令登出"+i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == 103) {
                            EventBus.getDefault().post(new ReloginEvent());
                        }
                    }
                });

            }


            @Override
            public void onError(String s, int i, String s1) {
                Logger.e("Agora 信令onError s:" + s + " i:" + i + " s1:" + s1);
                if (i == 208) {//用户已登录，再次发起登录会触发该错误 可以忽视该错误

                }
            }

            @Override
            public void onQueryUserStatusResult(final String name, final String status) {//1: 用户在线 0: 用户离线
                Logger.i("onQueryUserStatusResult name:" + name + " status:" + status);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (status.equals("1")) {
                            submitProblem(GUIDANCE);
                        } else if (status.equals("0")) {
                            showOfflinePrompt();
                        }
                    }
                });
            }
        });
    }
}
